<!DOCTYPE html>


<html lang="zh-Hans">
  

    <head>
      <meta charset="utf-8" />
       
      <meta name="keywords" content="前端，思考，感悟，代码，博客" />
       
      <meta name="description" content="向来缘浅，奈何情深。" />
      
      <meta
        name="viewport"
        content="width=device-width, initial-scale=1, maximum-scale=1"
      />
      <title>强大的moment.js |  飞蓬</title>
  <meta name="generator" content="hexo-theme-ayer">
      
      <link rel="shortcut icon" href="/favicon.ico" />
       
<link rel="stylesheet" href="/dist/main.css">

      
<link rel="stylesheet" href="/css/fonts/remixicon.css">

      
<link rel="stylesheet" href="/css/custom.css">
 
      <script src="https://cdn.staticfile.org/pace/1.2.4/pace.min.js"></script>
       
 

      <link
        rel="stylesheet"
        href="https://cdn.jsdelivr.net/npm/@sweetalert2/theme-bulma@5.0.1/bulma.min.css"
      />
      <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.min.js"></script>

      <!-- mermaid -->
      
      <style>
        .swal2-styled.swal2-confirm {
          font-size: 1.6rem;
        }
      </style>
    </head>
  </html>
</html>


<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-page3"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  强大的moment.js
</h1>
 

      
    </header>
     
    <div class="article-meta">
      <a href="/2020/07/01/page3/" class="article-date">
  <time datetime="2020-07-01T15:25:28.000Z" itemprop="datePublished">2020-07-01</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/js/">js</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> Word count:</span>
            <span class="post-count">622</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> Reading time≈</span>
            <span class="post-count">2 min</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <p>玩转moment</p>
<span id="more"></span>

<p>使用安装就不多赘述了，直接进入正题</p>
<h3 id="常用的几个方法（持续更新）"><a href="#常用的几个方法（持续更新）" class="headerlink" title="常用的几个方法（持续更新）"></a>常用的几个方法（持续更新）</h3><ol>
<li><p>获取当前时间  </p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title function_">moment</span>().<span class="title function_">format</span>(<span class="string">&quot;YYYY-MM-DD&quot;</span>)) <span class="comment">// 2020-07-01</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title function_">moment</span>().<span class="title function_">format</span>(<span class="string">&quot;YYYY年MM月DD日&quot;</span>)) <span class="comment">// 2020年07月01日</span></span><br></pre></td></tr></table></figure></li>
<li><p> 获取当前日期前一天与后一天的日期   </p>
</li>
</ol>
   <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title function_">moment</span>(<span class="string">&#x27;2020-07-01&#x27;</span>).<span class="title function_">subtract</span>(<span class="number">1</span>, <span class="string">&#x27;days&#x27;</span>).<span class="title function_">format</span>(<span class="string">&quot;YYYY-MM-DD&quot;</span>)) <span class="comment">// 2020-06-30</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title function_">moment</span>(<span class="string">&#x27;2020年07月01日&#x27;</span>).<span class="title function_">add</span>(<span class="number">1</span>, <span class="string">&#x27;days&#x27;</span>).<span class="title function_">format</span>(<span class="string">&quot;YYYY年MM月DD日&quot;</span>)) <span class="comment">// Invalid date</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="title function_">moment</span>(<span class="string">&#x27;20200701&#x27;</span>).<span class="title function_">add</span>(<span class="number">1</span>, <span class="string">&#x27;days&#x27;</span>).<span class="title function_">format</span>(<span class="string">&quot;YYYY年MM月DD日&quot;</span>)) <span class="comment">// 2020年07月02日</span></span><br></pre></td></tr></table></figure>

<ol start="3">
<li> 获取两个时间的差 值  </li>
</ol>
   <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> end_date = <span class="title function_">moment</span>().<span class="title function_">format</span>(<span class="string">&quot;YYYY-MM-DD&quot;</span>) <span class="comment">// 2020-07-01</span></span><br><span class="line"><span class="keyword">let</span> start_date = <span class="title function_">moment</span>(end_date).<span class="title function_">subtract</span>(<span class="number">1</span>, <span class="string">&#x27;month&#x27;</span>).<span class="title function_">format</span>(<span class="string">&quot;YYYY-MM-DD&quot;</span>) <span class="comment">// 2020-06-01</span></span><br><span class="line"><span class="title function_">moment</span>(end_date).<span class="title function_">diff</span>(start_date, <span class="string">&#x27;months&#x27;</span>) <span class="comment">// 1</span></span><br><span class="line"><span class="title function_">moment</span>(<span class="string">&#x27;2020-07-31&#x27;</span>).<span class="title function_">diff</span>(start_date, <span class="string">&#x27;months&#x27;</span>) <span class="comment">// 1</span></span><br><span class="line"><span class="title function_">moment</span>(<span class="string">&#x27;2020-06-30&#x27;</span>).<span class="title function_">diff</span>(start_date, <span class="string">&#x27;months&#x27;</span>) <span class="comment">// 0</span></span><br><span class="line"><span class="title function_">moment</span>(end_date).<span class="title function_">diff</span>(start_date, <span class="string">&#x27;weeks&#x27;</span>) <span class="comment">// 4</span></span><br><span class="line"><span class="title function_">moment</span>(end_date).<span class="title function_">diff</span>(start_date, <span class="string">&#x27;days&#x27;</span>) <span class="comment">// 30</span></span><br></pre></td></tr></table></figure>

<h3 id="发现问题"><a href="#发现问题" class="headerlink" title="发现问题"></a>发现问题</h3><p>diff()方法2020-07-01减去2020-06-01值为1，2020-07-31减去2020-06-01值也为1，2020-06-30减去2020-06-01值也为0</p>
<h3 id="项目实践"><a href="#项目实践" class="headerlink" title="项目实践"></a>项目实践</h3><p>有两个输入框，开始时间跟结束时间，要求：</p>
<ol>
<li><p>只能输入今天以及之前一年的时间</p>
</li>
<li><p>开始时间与结束时间最多相差一个月</p>
</li>
<li><p>隐藏要求，结束时间不能小于且不能等于开始时间</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> end_date = <span class="title function_">moment</span>().<span class="title function_">format</span>(<span class="string">&quot;YYYY-MM-DD&quot;</span>) <span class="comment">// 2020-07-01</span></span><br><span class="line"><span class="keyword">let</span> start_date = <span class="title function_">moment</span>(end_date).<span class="title function_">subtract</span>(<span class="number">1</span>, <span class="string">&#x27;year&#x27;</span>).<span class="title function_">format</span>(<span class="string">&quot;YYYY-MM-DD&quot;</span>) <span class="comment">// 2019-07-01</span></span><br></pre></td></tr></table></figure></li>
</ol>
<p>这样可以控制第一个条件，第二个条件会出现<strong>发现问题</strong>那样的情况，首先我们可以通过diff()函数取得两个时间月份month的差，然后在去判断两个时间天数days的差，月份差为1，天数差小于等于31就是符合条件的，但是好像有点麻烦了，下面看代码</p>
   <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> start_date = <span class="string">&#x27;2020-06-01&#x27;</span> <span class="comment">// 输入开始时间</span></span><br><span class="line"><span class="keyword">let</span> end_date1 = <span class="string">&#x27;2020-07-01&#x27;</span> <span class="comment">// 输入结束时间</span></span><br><span class="line"><span class="keyword">let</span> end_date2 = <span class="string">&#x27;2020-07-02&#x27;</span> <span class="comment">// 输入结束时间</span></span><br><span class="line"><span class="keyword">let</span> end_date3 = <span class="string">&#x27;2020-05-31&#x27;</span> <span class="comment">// 输入结束时间</span></span><br><span class="line"><span class="keyword">let</span> month1 = <span class="title function_">moment</span>(end_date1).<span class="title function_">subtract</span>(<span class="number">1</span>, <span class="string">&#x27;days&#x27;</span>).<span class="title function_">diff</span>(start_date, <span class="string">&#x27;months&#x27;</span>) <span class="comment">// 输出0</span></span><br><span class="line"><span class="keyword">let</span> month2 = <span class="title function_">moment</span>(end_date2).<span class="title function_">subtract</span>(<span class="number">1</span>, <span class="string">&#x27;days&#x27;</span>).<span class="title function_">diff</span>(start_date, <span class="string">&#x27;months&#x27;</span>) <span class="comment">// 输出1</span></span><br><span class="line">当month大于<span class="number">0</span>的时候，就是不符合条件</span><br><span class="line"><span class="keyword">let</span> day1 = <span class="title function_">moment</span>(end_date3).<span class="title function_">diff</span>(start_date, <span class="string">&#x27;days&#x27;</span>) <span class="comment">// 输出-1</span></span><br><span class="line">当day小于<span class="number">1</span>的时候，就是不符合条件</span><br></pre></td></tr></table></figure>

<p>更多内容可以查看<a target="_blank" rel="noopener" href="http://momentjs.cn/">moment.js中文网</a></p>
<hr>
<p>欢迎留言评论交流<br>转载本博客的文章请注明原始出处和作者</p>
 
      <!-- reward -->
      
      <div id="reword-out">
        <div id="reward-btn">
          Donate
        </div>
      </div>
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>Copyright： </strong>
          
          Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
          
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/js/" rel="tag">js</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/moment/" rel="tag">moment</a></li></ul>

    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2020/07/21/page5/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            文字排版神器 一分钟了解markdown
          
        </div>
      </a>
    
    
      <a href="/2020/06/23/page2/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">Flex:1是什么</div>
      </a>
    
  </nav>

  
   
    
    <script src="https://cdn.staticfile.org/twikoo/1.4.18/twikoo.all.min.js"></script>
    <div id="twikoo" class="twikoo"></div>
    <script>
        twikoo.init({
            envId: ""
        })
    </script>
 
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2019-2023
        <i class="ri-heart-fill heart_icon"></i> 飞蓬
      </li>
    </ul>
    <ul>
      <li>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>Visitors:<span id="busuanzi_value_site_uv"></span></span>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>Views:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>    
    </main>
    <div class="float_btns">
      <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

    </div>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/title.jpg" alt="飞蓬"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/about">关于我</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/404">公益404</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="/images/alipay.jpg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="/images/wechat.jpg">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-3.6.0.min.js"></script>
 
<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->
 
<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: ".tocbot",
    contentSelector: ".article-entry",
    headingSelector: "h1, h2, h3, h4, h5, h6",
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: "main",
    positionFixedSelector: ".tocbot",
    positionFixedClass: "is-position-fixed",
    fixedSidebarOffset: "auto",
  });
</script>

<script src="https://cdn.staticfile.org/jquery-modal/0.9.2/jquery.modal.min.js"></script>
<link
  rel="stylesheet"
  href="https://cdn.staticfile.org/jquery-modal/0.9.2/jquery.modal.min.css"
/>
<script src="https://cdn.staticfile.org/justifiedGallery/3.8.1/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->
 <!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.staticfile.org/photoswipe/4.1.3/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.staticfile.org/photoswipe/4.1.3/default-skin/default-skin.min.css">
<script src="https://cdn.staticfile.org/photoswipe/4.1.3/photoswipe.min.js"></script>
<script src="https://cdn.staticfile.org/photoswipe/4.1.3/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script> 
<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->
 
<script src="/js/busuanzi-2.3.pure.min.js"></script>
 
<!-- ClickLove -->
 
<script src="/js/clickLove.js"></script>
 
<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->
 
<link rel="stylesheet" href="/css/clipboard.css">
 <script src="https://cdn.staticfile.org/clipboard.js/2.0.10/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>
 
<!-- CanvasBackground -->
 
<script src="/js/dz.js"></script>
 
<script>
  if (window.mermaid) {
    mermaid.initialize({ theme: "forest" });
  }
</script>


    
    

  </div>
</body>

</html>